import java.util.*;

public class SnakePro {
    // 画布大小
    public final int ROW = 15;
    public final int COL = 30;

    // 定时器对象
    public Timer t = new Timer();

    // 定时时间
    public int ms = 300;

    public Canvas canvas = null;

    public Snake snake = null;

    public void p(String format, Object ... obj) {
        System.out.printf(format, obj);
    }

    public void show() {
        int i, j;
        char ch;

        Vt.gotoxy(1, 1);
        for (i = 0; i < ROW; ++i) {
            for (j = 0; j < COL; ++j) {
                ch = canvas.get(i, j);
                Vt.out("".valueOf(ch), snake.getColor(ch));
            }
            p("\n");
        }
    }

   public SnakePro() {
        //清屏和隐藏
        Vt.cmd(Vt.SCREEN).cmd(Vt.HIDE);
        // 终端输入初始化, 终端配置无缓冲输入 关闭回显
        Kyo.init();

        canvas = new Canvas(ROW, COL, '#');
        snake = new Snake(canvas);

        setTimer();
    }

    public void snakeExit() {
        // 最后显示一次画布
        show();
        // 关闭定时器
        t.cancel();
        // 终端配置还原 开启回显
        Kyo.exit();
        // 显示光标和定位画布下面
        Vt.cmd(Vt.SHOW).gotoxy(ROW + 1, 1);
        // 退出程序
        System.exit(0);
    }

    public void setTimer() {
        t.cancel();
        t = new Timer();
        t.schedule(new TimerTask() {
            public void run() {
                snake.draw();
                if (snake.move()) {
                    snakeExit();
                }
                show();
            }
        }, ms, ms);
    }

    public boolean keyHandle(int key) {
        switch (key) {
            case 27:
                return true;
            default:
                snake.setDir((char)key);
                break;
        }
        return false;
    }

    public void run() {
        while (true) {
            if (keyHandle(Kyo.key())) {
                break;
            }
        }
        snakeExit();
    }

    static public void main(String [] args) {
        SnakePro pro = new SnakePro();

        pro.run();
    }
}
